import 'dart:convert';

import 'package:aero_frisbee/app/model/login_respose_model/user_info_model.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AppStore {
  final SharedPreferences prefs;

  AppStore(this.prefs);

  String _languageCode = '';

  UserInfoModel? _userInfo;

  set languageCode(String value) {
    prefs.setString('languageCode.key', value);
    _languageCode = value;
  }

  String get languageCode {
    if (_languageCode.isNotEmpty) {
      return _languageCode;
    }
    return prefs.getString('languageCode.key') ?? "";
  }

  String _token = "";

  set token(String value) {
    prefs.setString('_token.key', value);
    _token = value;
  }

  String get token {
    if (_token.isNotEmpty) {
      return _token;
    }
    return prefs.getString('_token.key') ?? "";
  }

  set userInfo(UserInfoModel? userInfo) {
    if (userInfo != null) {
      prefs.setString('_userInfo.key', jsonEncode(userInfo.toJson()));
      _userInfo = userInfo;
    }
  }

  UserInfoModel? get userInfo {
    if (_userInfo != null) {
      return _userInfo;
    }
    final userInfoStr = prefs.getString('_userInfo.key');
    if (userInfoStr != null && userInfoStr.isNotEmpty) {
      return UserInfoModel.fromJson(jsonDecode(userInfoStr));
    }
    return null;
  }

  clear() {
    _token = '';
    prefs.remove('_token.key');
    prefs.remove('_userInfo.key');
  }
}
